package hedron.dialog;

import static hedron.i18n.Internationalization._;
import hedron.Application;
import hedron.db.model.Stock;
import hedron.db.model.StoreName;
import hedron.db.model.StoredStock;
import hedron.ui.UIFactory;
import java.util.ArrayList;
import java.util.Map;
import java.util.logging.Level;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

public class GroupStockDialog extends AbstractDialog {
	final StoreName storeName;
	final ArrayList<Stock> availableGroupings;

	Table groupingsTable;
	Spinner qtySpinner;
	Spinner buyPriceSpinner;
	Spinner sellPriceSpinner;
	StoredStock selectedStock;

	public GroupStockDialog(Shell parentShell, StoreName storeName) {
		super(parentShell);
		this.storeName = storeName;
		availableGroupings = Application.STOCKS.getAvailableGroupings(storeName);
	}

	@Override
	public void create() {
		super.create();
		setTitle(_("Dialog.MoveSplitStock.Title"));
		setMessage(_("Dialog.MoveSplitStock.Message") + " [ " + " ]", 0);
	}

	@Override
	protected void okPressed() {
		final long groupQty = (long) qtySpinner.getSelection();
		final long storeID = storeName.getID();
		try {
			final double buy = (double) buyPriceSpinner.getSelection() / 1000d;
			final double sell = (double) sellPriceSpinner.getSelection() / 1000d;
			Application.STORES.groupStock(selectedStock.STOCK_ID, storeID, groupQty, buy, sell);
			close();
		} catch (Exception e) {
			Application.log.log(Level.SEVERE, e.getMessage(), e);
			Application.setStatusMessage(2, e.getMessage());
		}
	}

	private static final String layout = "<layout columns=\"2\" width=\"400\" align=\"FILL\" valign=\"FILL\">"
			+ "<table id=\"groupingsTable\" colspan=\"2\" height=\"200\" fullselection=\"true\" align=\"FILL\" valign=\"FILL\"/>"
			+ "<label text=\"Column.BuyPrice\" width=\"100\" align=\"BEGINING\" valign=\"CENTER\"/>"
			+ "<spinner id=\"buyPriceSpinner\"  height=\"16\" align=\"FILL\" valign=\"CENTER\"/>"
			+ "<label text=\"Column.SellPrice\" align=\"BEGINING\" valign=\"CENTER\"/>"
			+ "<spinner id=\"sellPriceSpinner\"  height=\"16\" align=\"FILL\" valign=\"CENTER\"/>"
			+ "<label text=\"Column.Quantity\" align=\"BEGINING\" valign=\"CENTER\"/>"
			+ "<spinner id=\"qtySpinner\" height=\"16\" align=\"FILL\" valign=\"CENTER\"/>" + "</layout>";

	@Override
	void createContent(Composite parent) {
		Map<String, Control> components = UIFactory.createUI(parent, layout, null);
		groupingsTable = (Table) components.get("groupingsTable");

		groupingsTable.setRedraw(false);
		{
			TableColumn column = new TableColumn(groupingsTable, SWT.NONE);
			column.setText(_("Column.Stock"));
		}
		{
			TableColumn column = new TableColumn(groupingsTable, SWT.NONE | SWT.RIGHT);
			column.setText(_("Column.MaxQuantity"));
		}
		groupingsTable.setHeaderVisible(true);
		groupingsTable.setLinesVisible(true);

		groupingsTable.addListener(SWT.MouseUp, new Listener() {
			@Override
			public void handleEvent(Event event) {
				int selection = groupingsTable.getSelectionIndex();
				if (selection >= 0) {
					final Stock stock = (Stock) groupingsTable.getItem(selection).getData();

					if (selectedStock != null && selectedStock.STOCK_ID == stock.getID()) {
						// skip reseting buy, sell, and quantity values
						return;
					}
					int maxValue = (int) stock.QTY;

					selectedStock = new StoredStock();
					selectedStock.STOCK_ID = stock.getID();
					selectedStock.STORE_ID = storeName.getID();
					selectedStock.QTY = 1;
					Application.STORES.groupStockUpdateBuySell(selectedStock);
					qtySpinner.setValues(1, 1, maxValue, 0, 1, 1);
					buyPriceSpinner.setValues((int) (selectedStock.PRICE_BUY * 1000), 0, Integer.MAX_VALUE, 4, 10000,
							10000);
					sellPriceSpinner.setValues((int) (selectedStock.PRICE_SELL * 1000), 0, Integer.MAX_VALUE, 4, 10000,
							10000);
				} else {
					buyPriceSpinner.setValues(0, 0, 0, 4, 1, 1);
					sellPriceSpinner.setValues(0, 0, 0, 4, 1, 1);
					qtySpinner.setValues(0, 0, 0, 0, 1, 1);
					selectedStock = null;
				}
			}
		});

		for (Stock stock : availableGroupings) {
			TableItem item = new TableItem(groupingsTable, SWT.NONE);
			item.setData(stock);
			item.setText(0, stock.STOCK_NAME);
			item.setText(1, String.valueOf(stock.QTY));
		}
		groupingsTable.getColumn(0).pack();
		groupingsTable.getColumn(1).pack();
		groupingsTable.setRedraw(true);

		buyPriceSpinner = (Spinner) components.get("buyPriceSpinner");
		buyPriceSpinner.setValues(0, 0, 0, 4, 1, 1);

		sellPriceSpinner = (Spinner) components.get("sellPriceSpinner");
		sellPriceSpinner.setValues(0, 0, 0, 4, 1, 1);

		qtySpinner = (Spinner) components.get("qtySpinner");
		qtySpinner.setValues(0, 0, 0, 0, 1, 1);

		selectedStock = null;
	}
	private static final String layoutFooter = "<layout columns=\"3\" align=\"FILL\" valign=\"END\">"
			+ "<label align=\"FILL\" valign=\"CENTER\"/>"
			+ "<button id=\"cancel\" width=\"80\" height=\"20\" align=\"BEGINING\" valign=\"END\"/>"
			+ "<button id=\"ok\" default=\"true\" width=\"80\" height=\"20\" align=\"BEGINING\" valign=\"END\"/>"
			+ "</layout>";

	@Override
	void createFooter(Composite parent) {
		Composite grid = new Composite(parent, 0);
		Map<String, Control> components = UIFactory.createUI(grid, layoutFooter, null);

		Button cancel = (Button) components.get("cancel");
		cancel.setText("Cancel");
		cancel.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				setReturnCode(CANCEL);
				close();
			}
		});

		Button ok = (Button) components.get("ok");
		ok.setText("OK");
		ok.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				setReturnCode(OK);
				okPressed();
			}
		});
	}
}
